//
//  StageScene+Touch.swift
//  MixFruit
//
//  Created by remy on 2021/8/29.
//

extension StageScene {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard !isGameover else { return }
        guard let node = nowFruit, let touch = touches.first else { return }
        let location = touch.location(in: self)
        let space = node.size.width / 2.0
        node.run(.moveTo(x: max(min(location.x, UIScreen.width - space), space), duration: TIME_BEFORE_FALL))
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard !isGameover else { return }
        guard let node = nowFruit, let touch = touches.first else { return }
        let location = touch.location(in: self)
        let space = node.size.width / 2.0
        node.position.x = max(min(location.x, UIScreen.width - space), space)
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        if isGameover {
            guard let end = self.childNode(withName: "end") else { return }
            if end.atPoint(location) === end.childNode(withName: "restart") {
                resetGame()
            }
        } else {
            guard let node = nowFruit else { return }
            nowFruit = nil
            let space = node.size.width / 2.0
            node.position.x = max(min(location.x, UIScreen.width - space), space)
            self.run(.group([
                .sequence([
                    .wait(forDuration: TIME_BEFORE_FALL),
                    .run {
                        self.fruitBox.physicsFruit(node)
                    },
                    .wait(forDuration: TIME_BEFORE_APPEAR),
                    .run {
                        let newNode = self.fruitBox.randomFruit()
                        self.fruitWrap.addChild(newNode)
                        self.nowFruit = newNode
                        newNode.setScale(0.0)
                        newNode.run(.scale(to: 1.0, duration: self.TIME_APPEAR))
                    }
                ]),
                .sequence([
                    // 延迟加入下落水果组,防止下落过程中触发游戏状态检查
                    .wait(forDuration: STATE_UPDATE_DELAY),
                    .run {
                        // 已经合并消失不加入下落水果组
                        guard node.parent != nil else { return }
                        self.fallFruits.append(node)
                    }
                ])
            ]))
        }
    }
}
